#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import sys

import bottle
from bottle import route, run, request
from scpy.logger import get_logger
from scpy.xawesome_location import parse_location

from che168_query import search
from util import parse_city_id, parse_ltime, parse_car

reload(sys)
sys.setdefaultencoding("utf-8")
logger = get_logger(__file__)


def deal(car_list):
    min = car_list[0]['min']
    max = car_list[0]['max']
    for car in car_list:
        min = (car['min'], min)[car['min'] > min]
        max = (car['max'], min)[car['max'] < min]
    return "%s-%s" % (min, max)


@route('/car')
def car():
    request_params = request.GET.decode('utf-8')
    city = parse_location(request_params.get('city'))
    if not city:
        raise bottle.HTTPError(status=400, body="city error.")
    city = parse_city_id(city['cityShortName'])
    if not city:
        raise bottle.HTTPError(status=400, body="city error.")
    try:
        year, month = parse_ltime(request_params.get('licenseTime'))
    except Exception, e:
        raise bottle.HTTPError(status=400, body=e.message)
    try:
        mileage = float(request_params.get('mileage'))
        mileage = request_params.get('mileage')
    except:
        raise bottle.HTTPError(status=400, body='mileage error!!!')
    cars = parse_car(request_params.get('car').upper())
    if not cars:
        raise bottle.HTTPError(status=400, body='car error!!!')
    # try:
    #     accuracy = request_params.get('accuracy')
    #     accuracy = int(accuracy)
    # except Exception, e:
    #     accuracy = 5
    rst = search(cars=cars, city=city, year=year, month=month, mileage=mileage)
    if not rst:
        raise bottle.HTTPError(status=404, body='Not found.')

    if request_params.get('detailMode') == 'T':
        return json.dumps(rst, ensure_ascii=False)
    # return json.dumps(rst, ensure_ascii=False)
    return deal(rst)


SAIC_SERVER = bottle.default_app()

if __name__ == '__main__':
    port = 10000
    workers = 4
    run(host='0.0.0.0', port=port, server='gunicorn', workers=workers)
    # run(host='0.0.0.0', port=7003, debug=False)
